
open Graphics

let width = 500
let height= 500

let turtle_state () = 
  let (a, x, y) = Turtle.current_state () in
  let new_a = a in
  let new_x = int_of_float (x+.((float width)/.2.)) mod width in
  let new_y = int_of_float (y+.((float height)/.2.)) mod  height in
  (new_a, new_x, new_y)

let continue () =
  let ev = wait_next_event [Key_pressed] in
  ev.key <> 'q'

let print_pos () = 
  let (ca, cx, cy) = turtle_state () in 
  print_endline 
    ("\tangle: "      ^
	(string_of_float ca)           ^
	", x: " ^ (string_of_int cx) ^
	", y: " ^ (string_of_int cy))

let refresh_pos () =
  let (a, x, y) = turtle_state () in
  lineto x y

let init_set w h =
  open_graph (Printf.sprintf " %dx%d" w h);
  set_window_title "SUPa CL TURTLE";
  set_color black;
  let (a, x, y) = turtle_state () in
  moveto x y

let main () = 
  init_set width height;
  refresh_pos ();

  try
    let lexbuf = Lexing.from_channel stdin in
    print_pos ();
    while true do
      Turtle.prog Lexer.token lexbuf;
      print_pos ();
      refresh_pos ()
    done
  with 
      End_of_file | Graphic_failure("fatal I/O error") -> 
	close_graph (); exit 0
	  
let _ = Printexc.print main ()
